<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author FIRE
-->
<template>
  <div>
    <BasicDrawer
      v-bind="$attrs"
      :showFooter="true"
      :okAuth="'shop:order:cusFpApply:edit'"
      @register="registerDrawer"
      @ok="handleSubmit"
      width="80%"
    >
      <template #title>
        <Icon :icon="getTitle.icon" class="pr-1 m-1" />
        <span> {{ getTitle.value }} </span>
      </template>

      <Tabs v-model:activeKey="activeKey" tabPosition="left">
        <Tabs.TabPane key="1" :forceRender="true" tab="基本信息">
          <BasicForm @register="registerForm">
            <template #cusFpApplyRdsList>
              <Tabs v-model:activeKey="activeKeytab" tabPosition="top">
                <Tabs.TabPane :key="0" :forceRender="true" :tab="'明细清单'">
                  <BasicTable
                    @register="registerCusFpApplyRdsTable"
                    @row-click="handleCusFpApplyRdsRowClick"
                  />
                  <a-button
                    v-if="record.allowEdit"
                    class="mt-2"
                    @click="handleCusFpApplyRdsAdd"
                    v-auth="'shop:order:cusFpApply:edit'"
                  >
                    <Icon icon="ant-design:plus-circle-outlined" /> {{ t('新增') }}
                  </a-button>
                </Tabs.TabPane>

                <Tabs.TabPane :key="1" :forceRender="true" :tab="'汇总清单'">
                  <BasicTable @register="registerTablehz" @row-click="handleRowClickhz" />
                </Tabs.TabPane>
              </Tabs>
            </template>
            <template #kpSelect>
              <!-- v-model:value="itemCodes"
              :labelValue="itemNames" -->
              <ListSelect
                selectType="kpSelect"
                :checkbox="true"
                :params="queryParams"
                :selectList="listSelectRef"
                @select="handSelect"
              />
            </template>
            <template #listDetails>
              <div style="display: flex; justify-content: center">
                <!-- type="primary" -->
                <a-button class="mt-2" @click="handleListDetails">
                  <Icon icon="ant-design:eye-outlined" /> {{ t('查看订单详情') }}
                </a-button>
              </div>
            </template>
          </BasicForm>
        </Tabs.TabPane>

        <Tabs.TabPane key="2" :forceRender="true" tab="开票信息">
          <BasicForm @register="registerForm1">
            <template v-if="record.allowEdit" #btn>
              <a-button
                v-if="record.allowEdit"
                class="ml-6"
                type="success"
                @click="handleCusFpApplyqh"
                v-auth="'shop:order:cusFpApply:edit'"
              >
                <Icon icon="simple-line-icons:menu" /> {{ t('开票信息切换') }}
              </a-button>

              <a-button
                v-if="record.allowEdit"
                class="ml-6"
                @click="kpxxadd"
                v-auth="'bas:cus:basCusKpinfo:edit'"
              >
                <Icon icon="ant-design:plus-circle-outlined" /> {{ t('新增开票信息') }}
              </a-button>
            </template>

            <template #btnSelect>
              <!-- v-model:value="itemCodes"
              :labelValue="itemNames" -->
              <ListSelect
                selectType="kpxxSelect"
                :checkbox="false"
                :params="queryParams2"
                :selectList="listSelectRef2"
                @select="handSelect2"
              />
            </template>
          </BasicForm>
        </Tabs.TabPane>

        <Tabs.TabPane key="3" :forceRender="true" tab="开票结果">
          <BasicForm @register="registerForm2"> </BasicForm>
        </Tabs.TabPane>

        <!-- <Tabs.TabPane key="3" :forceRender="true" tab="表单栏目">
        <FormCol :colpop="colpop" />
      </Tabs.TabPane>

      <Tabs.TabPane key="4" :forceRender="true" tab="表单按钮">
        <FormBtn :colpop="colpop" />
      </Tabs.TabPane> -->
        <!-- 订单详情 -->
      </Tabs>
      <template #footer>
        <BpmButton
          v-model:bpmEntity="record"
          bpmEntityKey="id"
          formKey="soKpApply"
          completeText="提交"
          :loading="loadingRef"
          :auth="'shop:order:cusFpApply:edit'"
          @complete="handleSubmit"
          @success="handleSuccess"
          @close="closeDrawer"
        />
      </template>
    </BasicDrawer>

    <InputChildForm @register="registerchildFormDrawer" @success="tableReload" />
    <InputForm @register="registerFormDrawer" />
  </div>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsShopOrderCusFpApplyForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable, BasicColumn } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner, useDrawer } from '/@/components/Drawer';
  import {
    CusFpApply,
    cusFpApplySave,
    cusFpApplyForm,
    cusFpApplyListData,
    cusFpApplyChildList,
    cusFpApplyChildSumList,
    cusFpApplyaddRow,
    cusFpApplydelRow,
    cusFpApplyeditRow,
  } from '/@/api/shop/order/cusFpApply';
  import { BpmButton } from '/@/components/Bpm';
  import { Tabs } from 'ant-design-vue';
  import { ListSelect } from '/@/components/ListSelect';
  import InputForm from '/@/views/bas/cus/basCusKpinfo/form.vue';
  import InputChildForm from './childForm.vue';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('shop.order.cusFpApply');
  const { showMessage } = useMessage();
  const record = ref<CusFpApply>({} as CusFpApply);
  let listSelectRef = ref([]);
  let listSelectRef2 = ref([]);
  let queryParams = ref({});
  let queryParams2 = ref({});
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增开票申请') : t('查看开票申请'),
  }));
  const loadingRef = ref(false);
  const activeKey = ref<string>('1');
  const activeKeytab = ref<number>(0);
  const inputFormSchemas: FormSchema[] = [
    {
      label: t('基本信息'),
      field: 'bankInfo',
      component: 'FormGroup',
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('单据号'),
      field: 'djno',
      component: 'Input',
      dynamicDisabled: true,
      componentProps: {
        maxlength: 100,
      },
      show: false,
    },
    {
      label: t('客户编码'),
      field: 'cusCode',
      component: 'Input',
      dynamicDisabled: true,
      componentProps: {
        maxlength: 100,
      },
      required: true,
    },
    {
      label: t('客户名称'),
      field: 'basCus.name',
      component: 'Input',
      dynamicDisabled: true,
      componentProps: {
        maxlength: 100,
      },
      required: true,
    },
    {
      label: t('所属分公司'),
      field: 'companyName',
      component: 'Input',
      dynamicDisabled: true,
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('申请文员'),
      field: 'creator.userName',
      component: 'Input',
      dynamicDisabled: true,
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('申请时间'),
      field: 'createDate',
      component: 'DatePicker',
      dynamicDisabled: true,
      componentProps: {
        format: 'YYYY-MM-DD HH:mm',
        showTime: { format: 'HH:mm' },
      },
    },
    {
      label: t('申请状态'),
      field: 'kpStatus',
      component: 'Select',
      dynamicDisabled: true,
      componentProps: {
        dictType: 'cus_fp_status',
        allowClear: true,
      },
      // required: true,
    },

    {
      label: t('备注信息'),
      field: 'remarks',
      component: 'InputTextArea',
      // dynamicDisabled: true,
      componentProps: {
        maxlength: 64,
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('付款凭证'),
      field: 'dataMap2',
      component: 'Upload',
      // dynamicDisabled:true,
      componentProps: {
        loadTime: computed(() => record.value.__t),
        bizKey: computed(() => record.value.id),
        bizType: 'cusFpApply_image',
        uploadType: 'image',
        isPreview: true,
      },
      colProps: { lg: 24, md: 24 },
      // 文件上传的必填验证实例
      rules: [
        { required: true },
        {
          validator(_rule, value) {
            return new Promise((resolve, reject) => {
              const len = !value || value['cusFpApply_image__len'] || 0;
              if (len == 0) reject(t('请上传图片'));
              else resolve();
            });
          },
        },
      ],
    },
    {
      label: t('开票清单'),
      field: 'bankInfo1',
      component: 'FormGroup',
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('开票'),
      field: 'kpIds',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'kpSelect',
      show: false,
    },
    {
      label: t(''),
      field: 'cusFpApplyRdsList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'cusFpApplyRdsList',
    },
  ];
  const inputFormSchemas2: FormSchema[] = [
    // {
    //   label: t('开票结果'),
    //   field: 'kpStatus',
    //   component: 'Select',
    //   componentProps: {
    //     dictType: 'sys_yes_no',
    //     allowClear: true,
    //   },
    // },

    {
      label: t('发票链接'),
      field: 'fpUrl',
      component: 'Input',
      dynamicDisabled: true,
      componentProps: {
        maxlength: 100,
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('发票附件'),
      field: 'dataMap',
      component: 'Upload',
      dynamicDisabled: true,
      componentProps: {
        loadTime: computed(() => record.value.__t),
        bizKey: computed(() => record.value.id),
        bizType: 'cusFpApply_file',
        uploadType: 'file',
        // accept:'.pdf'
        // allowSuffixes:'.pdf'
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('完成时间'),
      field: 'overDate',
      component: 'DatePicker',
      dynamicDisabled: true,
      componentProps: {
        format: 'YYYY-MM-DD HH:mm',
        showTime: { format: 'HH:mm' },
      },
    },
    {
      label: t('开票人员'),
      field: 'overBy',
      component: 'Input',
      dynamicDisabled: true,
    },
    // {
    //   label: t('取消原因'),
    //   field: 'cancleRemarks',
    //   component: 'InputTextArea',
    //   dynamicDisabled: true,
    //   componentProps: {
    //     maxlength: 64,
    //   },
    //   colProps: { lg: 24, md: 24 },
    // },
  ];

  const inputFormSchemas1: FormSchema[] = [
    {
      label: t(''),
      field: 'btn',
      component: 'Input',
      slot: 'btn',
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('开票信息'),
      field: 'kpxxIds',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'btnSelect',
      show: false,
    },
    {
      label: t('抬头类型'),
      field: 'kpInfo.ctype',
      component: 'Select',
      dynamicDisabled: true,
      componentProps: {
        dictType: 'cus_fp_type',
        allowClear: true,
      },
      required: true,
    },

    {
      label: t('抬头名称'),
      field: 'kpInfo.cname',
      component: 'Input',
      dynamicDisabled: true,
      componentProps: {
        maxlength: 64,
      },
    },
    {
      label: t('联系电话'),
      field: 'kpInfo.contactInfo',
      component: 'Input',
      dynamicDisabled: true,
      componentProps: {
        maxlength: 64,
      },
    },
    {
      label: t('发票税号'),
      field: 'kpInfo.dutyNo',
      component: 'Input',
      dynamicDisabled: true,
      componentProps: {
        maxlength: 64,
      },
    },

    {
      label: t('开户银行'),
      field: 'kpInfo.bankName',
      component: 'Input',
      dynamicDisabled: true,
      componentProps: {
        maxlength: 64,
      },
    },

    {
      label: t('银行帐号'),
      field: 'kpInfo.bankCode',
      component: 'Input',
      dynamicDisabled: true,
      componentProps: {
        maxlength: 64,
      },
    },
    {
      label: t('单位号码'),
      field: 'kpInfo.dwNo',
      component: 'Input',
      dynamicDisabled: true,
      componentProps: {
        maxlength: 64,
      },
    },
    {
      label: t('单位地址'),
      field: 'kpInfo.dwAddr',
      component: 'Input',
      dynamicDisabled: true,
      componentProps: {
        maxlength: 64,
      },
    },
  ];

  const tableColumns: BasicColumn[] = [
    {
      title: t('订单号'),
      dataIndex: 'orderCode',
      sorter: false,
      width: 150,
      align: 'center',
    },
    {
      title: t('订单日期'),
      dataIndex: 'soMain.ddate',
      sorter: false,
      width: 100,
      align: 'center',
    },
    {
      title: t('存货编码'),
      dataIndex: 'basInv.cinvcode',
      key: 'a.inv_code',
      sorter: false,
      width: 120,
      align: 'left',
    },
    {
      title: t('存货名称'),
      dataIndex: 'basInv.cinvname',
      key: 'inv.cinvname',
      sorter: false,
      width: 180,
      align: 'left',
    },
    {
      title: t('规格型号'),
      dataIndex: 'basInv.cinvstd',
      key: 'inv.cinvstd',
      sorter: false,
      width: 100,
      align: 'left',
    },
    {
      title: t('单位'),
      dataIndex: 'basInv.unitName',
      key: 'inv.unit_name',
      sorter: false,
      width: 70,
      align: 'left',
    },

    {
      title: t('剩余数量'),
      dataIndex: 'sykpQty',
      sorter: false,
      width: 100,
      align: 'center',
    },
    {
      title: t('剩余金额'),
      dataIndex: 'sykpSum',
      sorter: false,
      width: 100,
      align: 'center',
    },
    {
      title: t('剩余折扣'),
      dataIndex: 'sykpSaleSum',
      sorter: false,
      width: 100,
      align: 'center',
    },
    {
      title: t('单价'),
      dataIndex: 'iprice',
      key: 'iprice',
      sorter: false,
      width: 80,
      align: 'right',
      fixed: 'right',
    },
    {
      title: t('本次数量'),
      dataIndex: 'iqty',
      sorter: false,
      width: 100,
      align: 'center',
      fixed: 'right',
    },
    {
      title: t('本次金额'),
      dataIndex: 'isum',
      sorter: false,
      width: 100,
      align: 'center',
      fixed: 'right',
    },
    {
      title: t('本次折扣'),
      dataIndex: 'saleSum',
      sorter: false,
      width: 200,
      align: 'center',
      fixed: 'right',
    },
  ];

  const tableColumns2: BasicColumn[] = [
    {
      title: t('存货编码'),
      dataIndex: 'basInv.cinvcode',
      key: 'a.inv_code',
      sorter: false,
      width: 120,
      align: 'left',
    },
    {
      title: t('存货名称'),
      dataIndex: 'basInv.cinvname',
      key: 'inv.cinvname',
      sorter: false,
      width: 180,
      align: 'left',
    },
    {
      title: t('规格型号'),
      dataIndex: 'basInv.cinvstd',
      key: 'inv.cinvstd',
      sorter: false,
      width: 100,
      align: 'left',
    },
    {
      title: t('单位'),
      dataIndex: 'basInv.unitName',
      key: 'inv.unit_name',
      sorter: false,
      width: 70,
      align: 'left',
    },
    {
      title: t('单价'),
      dataIndex: 'iprice',
      key: 'iprice',
      sorter: false,
      width: 80,
      align: 'right',
    },
    {
      title: t('本次数量'),
      dataIndex: 'iqty',
      sorter: false,
      width: 100,
      align: 'center',
    },
    {
      title: t('本次金额'),
      dataIndex: 'isum',
      sorter: false,
      width: 100,
      align: 'center',
    },
    // {
    //   title: t('本次折扣'),
    //   dataIndex: 'saleSum',
    //   sorter: false,
    //   width: 200,
    //   align: 'center',
    // },
  ];

  const [registerchildFormDrawer, { openDrawer: openDrawerchildForm }] = useDrawer();
  const [registerFormDrawer, { openDrawer }] = useDrawer();

  const [registerDrawerListDetails, { openDrawer: openDrawerListDetails }] = useDrawer();
  const [registerForm, { resetFields, setFieldsValue, getFieldsValue, validate, updateSchema }] =
    useForm({
      labelWidth: 120,
      schemas: inputFormSchemas,
      baseColProps: { lg: 12, md: 24 },
    });
  const [
    registerForm1,
    {
      resetFields: resetFields1,
      setFieldsValue: setFieldsValue1,
      getFieldsValue: getFieldsValue1,
      updateSchema: updateSchema1,
      validate: validate1,
    },
  ] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas1,
    baseColProps: { lg: 12, md: 24 },
  });

  const [
    registerForm2,
    {
      resetFields: resetFields2,
      setFieldsValue: setFieldsValue2,
      getFieldsValue: getFieldsValue2,
      validate: validate2,
      updateSchema: updateSchema2,
    },
  ] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas2,
    baseColProps: { lg: 12, md: 24 },
  });

  const [registerCusFpApplyRdsTable, cusFpApplyRdsTable] = useTable({
    actionColumn: {
      width: 80,
      actions: (record2: Recordable) => [
        {
          icon: 'clarity:note-edit-line',
          title: t('编辑明细清单'),
          onClick: handlechildForm.bind(this, { id: record2.id }),
          auth: 'shop:order:cusFpApply:edit',
          ifShow: () => record.value.allowEdit,
        },
        {
          icon: 'ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleCusFpApplyRdsDelete.bind(this, record2),
          },
          auth: 'shop:order:cusFpApply:edit',
          ifShow: () => record.value.allowEdit,
        },
      ],
    },
    api: cusFpApplyChildList,
    rowKey: 'id',
    pagination: false,
    columns: tableColumns,
    // formConfig: searchForm2,
    // useSearchForm: true,
    beforeFetch: (params) => {
      params['applyId.id'] = record.value.id;
      console.log(params);
      return params;
    },
    // bordered: true,
    // size: 'small',
    // inset: true,
    maxHeight: 300,
    canResize: true,
    showTableSetting: false,
    immediate: false,
    showSummary: true,
    summaryFunc: handleSummary,
  });

  const [registerTablehz, hzTable] = useTable({
    api: cusFpApplyChildSumList,
    rowKey: 'id',
    pagination: false,
    // formConfig: searchForm2,
    beforeFetch: (params) => {
      params['applyId.id'] = record.value.id;
      console.log(params);
      return params;
    },
    // useSearchForm: true,
    columns: tableColumns2,
    // bordered: true,
    // size: 'small',
    // inset: true,
    maxHeight: 300,
    canResize: true,
    showTableSetting: false,
    immediate: false,
  });

  async function setCusFpApplyRdsTableData(_res: Recordable) {
    cusFpApplyRdsTable.setColumns([
      {
        title: t('订单号'),
        dataIndex: 'orderCode',
        sorter: false,
        width: 150,
        align: 'center',
      },
      {
        title: t('订单日期'),
        dataIndex: 'soMain.ddate',
        sorter: false,
        width: 100,
        align: 'center',
      },
      {
        title: t('存货编码'),
        dataIndex: 'basInv.cinvcode',
        key: 'a.inv_code',
        sorter: false,
        width: 120,
        align: 'left',
      },
      {
        title: t('存货名称'),
        dataIndex: 'basInv.cinvname',
        key: 'inv.cinvname',
        sorter: false,
        width: 180,
        align: 'left',
      },
      {
        title: t('规格型号'),
        dataIndex: 'basInv.cinvstd',
        key: 'inv.cinvstd',
        sorter: false,
        width: 100,
        align: 'left',
      },
      {
        title: t('单位'),
        dataIndex: 'basInv.unitName',
        key: 'inv.unit_name',
        sorter: false,
        width: 70,
        align: 'left',
      },
      {
        title: t('单价'),
        dataIndex: 'iprice',
        key: 'iprice',
        sorter: false,
        width: 80,
        align: 'right',
      },
      {
        title: t('剩余数量'),
        dataIndex: 'sykpQty',
        sorter: false,
        width: 100,
        align: 'center',
        fixed: 'right',
      },
      {
        title: t('剩余金额'),
        dataIndex: 'sykpSum',
        sorter: false,
        width: 100,
        align: 'center',
        fixed: 'right',
      },
      {
        title: t('剩余折扣'),
        dataIndex: 'sykpSaleSum',
        sorter: false,
        width: 100,
        align: 'center',
        fixed: 'right',
      },
      {
        title: t('本次数量'),
        dataIndex: 'iqty',
        sorter: false,
        width: 100,
        align: 'center',
        fixed: 'right',
      },
      {
        title: t('本次金额'),
        dataIndex: 'isum',
        sorter: false,
        width: 100,
        align: 'center',
        fixed: 'right',
      },
      {
        title: t('本次折扣'),
        dataIndex: 'saleSum',
        sorter: false,
        width: 200,
        align: 'center',
        fixed: 'right',
      },
    ]);
    cusFpApplyRdsTable.setTableData(record.value.cusFpApplyRdsList || []);
  }

  async function setTableDatahz(_res: Recordable) {
    hzTable.setColumns([
      {
        title: t('存货编码'),
        dataIndex: 'basInv.cinvcode',
        key: 'a.inv_code',
        sorter: false,
        width: 120,
        align: 'left',
      },
      {
        title: t('存货名称'),
        dataIndex: 'basInv.cinvname',
        key: 'inv.cinvname',
        sorter: false,
        width: 180,
        align: 'left',
      },
      {
        title: t('规格型号'),
        dataIndex: 'basInv.cinvstd',
        key: 'inv.cinvstd',
        sorter: false,
        width: 100,
        align: 'left',
      },
      {
        title: t('单位'),
        dataIndex: 'basInv.unitName',
        key: 'inv.unit_name',
        sorter: false,
        width: 70,
        align: 'left',
      },
      {
        title: t('单价'),
        dataIndex: 'iprice',
        key: 'iprice',
        sorter: false,
        width: 80,
        align: 'right',
      },
      {
        title: t('本次数量'),
        dataIndex: 'iqty',
        sorter: false,
        width: 100,
        align: 'center',
      },
      {
        title: t('本次金额'),
        dataIndex: 'isum',
        sorter: false,
        width: 100,
        align: 'center',
      },
      {
        title: t('本次折扣'),
        dataIndex: 'saleSum',
        sorter: false,
        width: 200,
        align: 'center',
      },
    ]);
    hzTable.setTableData(record.value.cusFpApplyRdsList || []);
  }

  function handleCusFpApplyRdsRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }
  function handleRowClickhz(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function kpxxadd() {
    // router.push({
    //   path: '/bas/cus/basCusKpinfo/list',
    // });
    // setTimeout(closeDrawer);
    openDrawer(true, {
      cusCode: record.value.cusCode,
      'basCus.name': record.value.basCus.name,
    });
  }

  function tableReload() {
    cusFpApplyRdsTable.reload();
    hzTable.reload();
  }
  async function handSelect(selectData) {
    console.log(selectData, 'selectData====');
    let selIds = selectData.map((item) => {
      return item.sodid;
    });
    let data = {
      id: record.value.id,
      selIds: selIds.join(','),
    };
    const res = await cusFpApplyaddRow(data);
    tableReload();
    showMessage(res.message);
  }

  function handSelect2(selectData) {
    console.log(selectData, 'selectData====');
    let obj = {
      kpInfo: {
        ...selectData[0],
      },
    };
    setFieldsValue1(obj);
    // ctype
    // cname
    // dutyNo
    // contactInfo
    // bankName
    // bankCode
    // dwNo
    // dwAddr
  }

  function handleSummary(tableData: Recordable[]) {
    // const sykpQty = tableData.reduce((prev, next) => {
    //   prev += next.sykpQty ? next.sykpQty : 0;
    //   return prev;
    // }, 0);

    // const sykpSum = tableData.reduce((prev, next) => {
    //   prev += next.sykpSum ? next.sykpSum : 0;
    //   return prev;
    // }, 0);

    // const sykpSaleSum = tableData.reduce((prev, next) => {
    //   prev += next.sykpSaleSum ? next.sykpSaleSum : 0;
    //   return prev;
    // }, 0);

    const iqty = tableData.reduce((prev, next) => {
      prev += next.iqty ? next.iqty : 0;
      return prev;
    }, 0);
    const isum = tableData.reduce((prev, next) => {
      prev += next.isum ? next.isum : 0;
      return prev;
    }, 0);

    const saleSum = tableData.reduce((prev, next) => {
      prev += next.saleSum ? next.saleSum : 0;
      return prev;
    }, 0);

    const zkl = ((saleSum / isum) * 100).toFixed(2);

    return [
      {
        // _row: '合计',
        _index: '合计',
        // 'sykpQty': sykpQty,
        // 'sykpSum': sykpSum,
        // 'sykpSaleSum': sykpSaleSum,
        // 'applyRds':{
        //   sykpQty,
        //   sykpSum,
        //   sykpSaleSum,
        // },
        iqty: iqty,
        isum: isum,
        saleSum: saleSum + `（折扣率:${zkl}%）`,
      },
    ];
  }

  function handleCusFpApplyRdsAdd() {
    // cusFpApplyRdsTable.insertTableDataRecord({
    //   id: new Date().getTime(),
    //   isNewRecord: true,
    //   editable: true,
    // });
    listSelectRef.value = [];
    document.getElementById('form_item_kpIds')?.click();
  }

  function handleCusFpApplyqh() {
    // cusFpApplyRdsTable.insertTableDataRecord({
    //   id: new Date().getTime(),
    //   isNewRecord: true,
    //   editable: true,
    // });
    listSelectRef2.value = [];
    document.getElementById('form_item_kpxxIds')?.click();
  }

  function handleListDetails() {
    openDrawerListDetails(true, { id: record.value.id });
  }

  function handlechildForm(record2) {
    openDrawerchildForm(true, {
      id: record2.id,
      'applyId.id': record.value.id,
    });
  }

  async function handleCusFpApplyRdsDelete(record2: Recordable) {
    // await cusFpApplyRdsTable.deleteTableDataRecord(record);
    const res = await cusFpApplydelRow({
      id: record.value.id,
      selIds: record2.id,
    });
    showMessage(res.message);
    tableReload();
  }

  async function getCusFpApplyRdsList() {
    let cusFpApplyRdsListValid = true;
    let cusFpApplyRdsList: Recordable[] = [];
    for (const record of cusFpApplyRdsTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        cusFpApplyRdsListValid = false;
      }
      cusFpApplyRdsList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of cusFpApplyRdsTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      cusFpApplyRdsList.push({
        ...record,
        status: '1',
      });
    }
    if (!cusFpApplyRdsListValid) {
      throw { errorFields: [{ name: ['cusFpApplyRdsList'] }] };
    }
    return cusFpApplyRdsList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    await resetFields1();
    await resetFields2();
    const res = await cusFpApplyForm({ id: data.id });
    record.value = (res.cusFpApply || {}) as CusFpApply;
    record.value = { ...data, ...record.value };
    queryParams.value = {
      cusCode: record.value.cusCode,
    };
    queryParams2.value = {
      cusCode: record.value.cusCode,
    };
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setFieldsValue1(record.value);
    setFieldsValue2(record.value);
    // setCusFpApplyRdsTableData(res);
    // setTableDatahz(res);
    cusFpApplyRdsTable.reload();
    hzTable.reload();
    await setDrawerProps({ loading: false });
    updateSchema([
      {
        field: 'bankInfo',
        label: t(`基本信息 (${record.value.djno})`),
      },
      {
        field: 'remarks',
        dynamicDisabled: record.value.allowEdit ? false : true,
      },
      {
        field: 'dataMap2',
        dynamicDisabled: record.value.allowEdit ? false : true,
      },
    ]);
    updateSchema1([
      {
        field: 'btn',
        ifShow: record.value.allowEdit ? true : false,
      },
    ]);
    setTimeout(() => {
      updateSchema2([
        {
          field: 'fpUrl',
          dynamicDisabled: record.value.bpm.activityId == 'uploadFp' ? false : true,
        },
        {
          field: 'dataMap',
          dynamicDisabled: record.value.bpm.activityId == 'uploadFp' ? false : true,
        },
      ]);
    }, 1000);
  });

  async function handleSubmit() {
    try {
      const data1 = await validate();
      const data2 = await validate1();
      const data3 = await validate2();

      if (
        record.value.bpm.activityId == 'uploadFp' &&
        !data3.fpUrl &&
        !data3.dataMap.cusFpApply_file__len
      ) {
        showMessage('发票链接和发票附件请至少填写一项！');
        return;
      }

      let data = {
        ...data1,
        ...data2,
        ...data3,
      };
      data.bpm = record.value.bpm; // 流程信息
      data.status = record.value.status; // 提交状态
      loadingRef.value = true;

      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      data.cusFpApplyRdsList = []
      //data.cusFpApplyRdsList = await getCusFpApplyRdsList();
      // console.log('submit', params, data, record);
      const res = await cusFpApplySave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      loadingRef.value = false;
      setDrawerProps({ confirmLoading: false });
    }
  }

  async function handleSuccess() {
    emit('success');
  }
</script>
